﻿using DingTalk.Api.Request;
using DingTalk.Api.Response;
using DingTalk.Api;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;
using System.Text;
using Suite;
using hnrzxt.data;
using Microsoft.AspNetCore.Mvc;
using hnrzxt.Controllers;
using hnrzxt.Models;
using System.Reflection;
using NuGet.Protocol;
using Nancy.Json;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Components.Forms;
using Tea;
using AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models;
using System;
using Microsoft.VisualBasic;
using System.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Net;

namespace hnrzxt.tool
{


    public static class Extensions
    {
        public static string GetString<K,V>(this IDictionary<K,V> dict)
        {
            var items = dict.Select(kvp => kvp.ToString());
            return string.Join(", ", items);
        }
    }
 
    public class PubFunc:Controller
    {

        private readonly ApplicationDbContext _db;
        public PubFunc(ApplicationDbContext db)
        {
            _db = db;
        }

        public static void WriteLog(string LogStr, string FileName, Boolean Addto)
        {
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "Logs" + "\\" + DateTime.Now.ToString("yyyyMM");
            string filepathname = filepath + "\\" + FileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";

            if (FileName == "") FileName = "Err";

            if (Directory.Exists(filepath) == false)
            {
                Directory.CreateDirectory(filepath);
            }
            if (Addto)
                filepathname = filepath + "\\" + FileName + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            else
                filepathname = filepath + "\\" + FileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";

            FileStream fs = new FileStream(filepathname, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            if (Addto) fs.Position = fs.Length;//追加记录日志 
            sw.WriteLine(LogStr);
            sw.Close();
        }
        //获取钉钉表单数据
        public OapiProcessinstanceGetResponse Getrsp(string processInstanceId)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
            req.ProcessInstanceId = processInstanceId;
            OapiProcessinstanceGetResponse rsp = client.Execute(req, HNWZ_API.Token());
            return rsp;
        }
        public string Getformcomponentvalues(string processInstanceId)
        {
            var rsp = Getrsp(processInstanceId);
            
            //解析钉钉表单数据
            JObject ProcessData = (JObject)JsonConvert.DeserializeObject(rsp.Body.ToString());
            string process_instance = ProcessData["process_instance"].ToString();

            JObject FormData = (JObject)JsonConvert.DeserializeObject(process_instance);
            string form_component_values = FormData["form_component_values"].ToString();
            return form_component_values;
        }

        public static T ConvertDic<T>(Dictionary<string, object> dic)
        {           
                T model = Activator.CreateInstance<T>();  //泛型的初始化
                PropertyInfo[] modelPro = model.GetType().GetProperties(); //获取类型T中所有的属性字段
                if (modelPro.Length > 0 && dic.Count > 0)
                {
                    for (int i = 0; i < modelPro.Length; i++)
                    {
                        if (dic.ContainsKey(modelPro[i].Name)) //判断dic中Key是否和实体类中的属性名相同,相同则保存。也就是想要什么数据定义什么有属性的实体类
                        {
                            modelPro[i].SetValue(model, dic[modelPro[i].Name], null);
                        }
                    }

                }
            return model;
           
        }
        //获取行政区域id
        private string getAreaID(string areaID)
        {
            //DataSet ds = new DataSet();

            //WriteLog(DateTime.Now + " SQL：select F_Id from sys_area where F_Layers='" + layer + "' and F_FullName='" + name + "'", "HrLog", true);
            sys_area area = new();
            List<sys_area> areas = _db.sys_area.Where(p => p.F_FullName == areaID).ToList();

            {
                WriteLog(areas[0].F_Id + areas[0].F_FullName,"AREALog",true);
                return areas[0].F_Id;
            }

            
        }
        //通讯录企业部门更新。
        public Dictionary<string, object> UpDeptToHR(long deptId, string token)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.DeptId = deptId;
            OapiV2DepartmentGetResponse rsp = client.Execute(req, token);
            Console.WriteLine(rsp.Body);
            Dictionary<string, object> DeptForm = new();

            //解析钉钉表单数据
            JObject Result = (JObject)JsonConvert.DeserializeObject(rsp.Body.ToString());
            string result = Result["result"].ToString();


            JObject FormData = (JObject)JsonConvert.DeserializeObject(result);

            WriteLog(DateTime.Now + " "+ FormData["dept_id"].ToString(),"result",true);

            DeptForm.Add("DingID", FormData["dept_id"].ToString());
            DeptForm.Add("DingOrgName", FormData["name"].ToString());
            DeptForm.Add("DingParentOrgId", FormData["parent_id"].ToString());
            DeptForm.Add("DingRemark", "接口更新");
            DeptForm.Add("sort", FormData["order"].ToString());

            DingOrga org = ConvertDic<DingOrga>(DeptForm);
            if (DeptForm != null)
            {
                _db.DingOrga.Update(org);
                _db.SaveChanges();

            }

            var str = Extensions.GetString(DeptForm);

            WriteLog(str, "DeptformLog", true);
            return DeptForm;
        }
        public Dictionary<string, object> CreateDeptToHR(long deptId, string token)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.DeptId = deptId;
            OapiV2DepartmentGetResponse rsp = client.Execute(req, token);
            Console.WriteLine(rsp.Body);
            Dictionary<string, object> DeptForm = new();

            //解析钉钉表单数据
            JObject Result = (JObject)JsonConvert.DeserializeObject(rsp.Body.ToString());
            string result = Result["result"].ToString();


            JObject FormData = (JObject)JsonConvert.DeserializeObject(result);
            WriteLog(DateTime.Now + " " + FormData["dept_id"].ToString(), "result", true);

            DeptForm.Add("DingID", FormData["dept_id"].ToString());
            DeptForm.Add("DingOrgName", FormData["name"].ToString());
            DeptForm.Add("DingParentOrgId", FormData["parent_id"].ToString());
            DeptForm.Add("DingRemark", "接口创建");
            DeptForm.Add("sort", FormData["order"].ToString());

            DingOrga org = ConvertDic<DingOrga>(DeptForm);
            if (DeptForm != null)
            {
                _db.DingOrga.Add(org);
                _db.SaveChanges();

            }

            var str = Extensions.GetString(DeptForm);

            WriteLog(str, "DeptformLog", true);
            return DeptForm;
        }
        public void DeleteDeptToHR(long deptId)
        {
            var de = _db.DingOrga.Where(p => p.DingID == deptId).SingleOrDefault();
            var dept = _db.DingOrga.Find(de.DingID);

            //var dept = _db.DingOrga.Find(de.id);
            if (deptId != null)
            {
                _db.DingOrga.Remove(dept);
                _db.SaveChanges();

            }

        }
        public static AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client(config);
        }
        public static List<string> GetoneSp(string processInstanceId)
        {
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client client = CreateClient();
            GetProcessInstanceHeaders getProcessInstanceHeaders = new()
            {
                XAcsDingtalkAccessToken = HNWZ_API.Token()
            };
            GetProcessInstanceRequest getProcessInstanceRequest = new()
            {
                ProcessInstanceId = processInstanceId,
            };
            List<string> fcv = new();

            try
            {
                List<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult.GetProcessInstanceResponseBodyResultFormComponentValues> values = client.GetProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions()).Body.Result.FormComponentValues;//返回的是response类型
                for (var i = 0; i < values.Count; i++)
                {
                    fcv.Add(values[i].Value);
                }
                return fcv;
            }
            catch (TeaException err)
            {

                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return null;
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return null;
            }
        }        
        public static List<string> GetFileId(string processInstanceId)
        {
            var a = GetoneSp(processInstanceId);
            List<string> value = new List<string>();
            List<string> value2 = new List<string>();
            value.Add(a[16].ToString());
            value.Add(a[19].ToString());
            if (value.Count == 0)
                return null;
            //return null;
            else
            {
                var brr = JArray.Parse(value[0].ToString());
                var crr = JArray.Parse(value[1].ToString());
                for (var i = 0; i < crr.Count; i++)
                {
                    value2.Add(crr[i]["rowValue"][2]["value"][0]["fileId"].ToString());
                }
                var bbrr = JArray.Parse(brr[0]["rowValue"][7]["value"].ToString());
                for (var i = 0; i < bbrr.Count; i++)
                {
                    value2.Add(bbrr[i]["fileId"].ToString());
                }
                return value2;
            }
        }
        public static List<string> GetFileName(string processInstanceId)
        {
            var a = GetoneSp(processInstanceId);
            List<string> value = new List<string>();
            List<string> value2 = new List<string>();
            value.Add(a[16].ToString());
            value.Add(a[19].ToString());
            if (value.Count == 0)
                return null;
            //return null;
            else
            {
                var brr = JArray.Parse(value[0].ToString());
                var crr = JArray.Parse(value[1].ToString());
                for (var i = 0; i < crr.Count; i++)
                {
                    value2.Add(crr[i]["rowValue"][2]["value"][0]["fileName"].ToString());
                }
                var bbrr = JArray.Parse(brr[0]["rowValue"][7]["value"].ToString());
                for (var i = 0; i < bbrr.Count; i++)
                {
                    value2.Add(bbrr[i]["fileName"].ToString());
                }
                return value2;
            }
        }
        public static string GetDownLoadurl(string processInstanceId,string fileid)
        {
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.GrantProcessInstanceForDownloadFileHeaders grantProcessInstanceForDownloadFileHeaders = new()
            {
                XAcsDingtalkAccessToken = HNWZ_API.Token()
            };
            //List<AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.GrantProcessInstanceForDownloadFileRequest> grantProcessInstanceForDownloadFileRequest = new();
            //for(var i = 0; i < value2.Count; i++)
            //{
            //    grantProcessInstanceForDownloadFileRequest.AddRange(processInstanceId, value2[i].ToString());
            //}
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.GrantProcessInstanceForDownloadFileRequest grantProcessInstanceForDownloadFileRequest = new()
            {
                ProcessInstanceId = processInstanceId,

                FileId = fileid,
            };
            try
            {
                GrantProcessInstanceForDownloadFileResponse response =  client.GrantProcessInstanceForDownloadFileWithOptions(grantProcessInstanceForDownloadFileRequest, grantProcessInstanceForDownloadFileHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
                return response.Body.Result.DownloadUri.ToString();
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return err.Message;
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return _err.Message;
            }
        }
        public string GetUserPhone(string userid)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new();
            string access_token = HNWZ_API.Token();
            req.Userid = userid;
            OapiV2UserGetResponse rsp = client.Execute(req, access_token);
            Console.WriteLine(rsp.Body);

            JObject string_user_phone = (JObject)JsonConvert.DeserializeObject(rsp.Body.ToString());
            return string_user_phone["result"]["mobile"].ToString();
        }
        public void FiletoHr(string processInstanceId)
        {
            var fileCount = PubFunc.GetFileId(processInstanceId).Count;
            var fileid = PubFunc.GetFileId(processInstanceId);
            var filename = PubFunc.GetFileName(processInstanceId);

            PubFunc.WriteLog("获取文件：" + fileCount + " 第一个附件id: " + fileid[0] + "第一个附件name" + filename[0], "FileLog", true);

            //运行下载链接
            for (var i = 0; i < fileCount; i++)
            {
                string url = PubFunc.GetDownLoadurl(processInstanceId, fileid[i]);
                PubFunc.WriteLog("第" + i + "个: " + url, "UrlLog", true);

                WebClient webClient = new();
                webClient.DownloadFile(url, "D:\\publish\\wwwroot\\UploadFiles\\" + filename[i]);

                PubFunc.WriteLog("获取文件：" + i + " 附件id: " + fileid[i] + " 附件name" + filename[i], "FileLog", true);
                PubFunc.WriteLog(url, "UrlLog", true);
            }
        }

        //一、录用审批
        public void AddZLinfo(string processInstanceId)
        {
            WriteLog("AddZLinfo", "ZLLog", true);
            try
            { 
                string form_component_values = Getformcomponentvalues(processInstanceId);
                var formData = JArray.Parse(form_component_values);
                Dictionary<string, object> Jbxxdic = new();
                Dictionary<string, object> Zlxxdic = new();
                Dictionary<string, object> Gwxxdic = new();
                string a = null;
                string uuid = Guid.NewGuid().ToString();
                foreach (var form in formData)
                {
                    switch (form["name"].ToString())
                    {
                        case "录用人员姓名":
                            Jbxxdic.Add("name", form["value"].ToString());
                            break;
                        case "电话":
                            Jbxxdic.Add("phonenumber", form["value"].ToString());
                            break;
                        case "岗位":
                            Gwxxdic.Add("gangwei", form["value"].ToString());
                            break;
                        case "部门":
                            Gwxxdic.Add("department", form["value"].ToString());
                            break;
                        case "层级":
                            if (form["value"].ToString() == "高层")
                            {
                                Gwxxdic.Add("cengji", "1");
                            }
                            else if (form["value"].ToString() == "中层")
                            {
                                Gwxxdic.Add("cengji", "2");
                            }
                            else if (form["value"].ToString() == "基层")
                            {
                                Gwxxdic.Add("cengji", "3");
                            };
                            break;
                        case "行政级别":
                            if (form["value"].ToString() == "总经理")
                            {
                                Gwxxdic.Add("zhiji", "1");
                                a = "总经理";
                            }
                            else if (form["value"].ToString() == "副总经理")
                            {
                                Gwxxdic.Add("zhiji", "2");
                                a = "副总经理";
                            }
                            else if (form["value"].ToString() == "总经理助理")
                            {
                                Gwxxdic.Add("zhiji", "3");
                                a = "总经理助理";
                            }
                            else if (form["value"].ToString() == "部长")
                            {
                                Gwxxdic.Add("zhiji", "4");
                                a = "部长";
                            }
                            else if (form["value"].ToString() == "副部长")
                            {
                                Gwxxdic.Add("zhiji", "5");
                                a = "副部长";
                            }
                            else if (form["value"].ToString() == "部长助理")
                            {
                                Gwxxdic.Add("zhiji", "6");
                                a = "部长助理";
                            }
                            else if (form["value"].ToString() == "主任")
                            {
                                Gwxxdic.Add("zhiji", "7");
                                a = "主任";
                            }
                            else if (form["value"].ToString() == "副主任")
                            {
                                Gwxxdic.Add("zhiji", "8");
                                a = "副主任";
                            }
                            else if (form["value"].ToString() == "初级主管")
                            {
                                Gwxxdic.Add("zhiji", "9");
                                a = "初级主管";
                            }
                            else if (form["value"].ToString() == "一级主管")
                            {
                                Gwxxdic.Add("zhiji", "10");
                                a = "一级主管";
                            }
                            else if (form["value"].ToString() == "二级主管")
                            {
                                Gwxxdic.Add("zhiji", "11");
                                a = "二级主管";
                            }
                            else if (form["value"].ToString() == "专员")
                            {
                                Gwxxdic.Add("zhiji", "12");
                                a = "专员";
                            };
                            break;
                        case "面试人员姓名":
                            Zlxxdic.Add("Rz", form["value"].ToString());
                            break;
                        case "入职日期":
                            Gwxxdic.Add("workstarttime", form["value"].ToString());
                            break;
                        case "录用来源":
                            Zlxxdic.Add("Lyscrouce", form["value"].ToString());
                            if (form["value"].ToString() != "关系推荐")
                            {
                                WriteLog("非关系推荐"+ form["value"].ToString(), "RELog", true);
                                Zlxxdic.Add("Remark", "非关系推荐");
                            }
                            break;
                        case "推荐人":
                            if (form.ToString().Contains("value"))
                            {
                               if(form["value"].ToString() != "null")
                               {
                                    Zlxxdic.Add("Remark", form["value"].ToString());
                               }                               
                            }
                            break;
                        case "是否背景调查":
                            if (form["value"].ToString() == "否")
                            {
                                Zlxxdic.Add("Bjdc", "没有背景调查");
                            }
                            break;
                        case "背景调查报告":
                            if (form.ToString().Contains("value"))
                            {
                                if (form["value"].ToString() != "null")
                                {
                                    WriteLog(form.ToString(), "RELog", true);
                                    Console.WriteLine();
                                    Zlxxdic.Add("Bjdc", form["value"].ToString());
                                }
                            }
                            break;
                        case "附件一：《人才登记表》":
                            if (form.ToString().Contains("value"))
                            {
                                if (form["value"].ToString() != "null")
                                {
                                    JArray jarc = JArray.Parse(form["value"].ToString());
                                    string str = null;
                                    List<string> list = new List<string>();
                                    for(var i = 0; i < jarc.Count; i++) 
                                    { 
                                        JToken jt = JToken.Parse(jarc[i].ToString());
                                        list.Add(jt["fileName"].ToString());
                                        str = string.Join(",", list);
                                    }
                                    Zlxxdic.Add("Yrbm",str);
                                }
                                else
                                {
                                    Zlxxdic.Add("Yrbm", "无附件");
                                }
                            }
                            else
                            {                                
                                Zlxxdic.Add("Yrbm", "无附件");                               
                            }

                            break;
                        case "附件二：《面试评定表》":
                            if (form.ToString().Contains("value"))
                            {
                                if (form["value"].ToString() != "null")
                                {
                                    JArray jams = JArray.Parse(form["value"].ToString());
                                    string str = null;
                                    List<string> list = new List<string>();
                                    for (var i = 0; i < jams.Count; i++)
                                    {
                                        JToken jtms = JToken.Parse(jams[i].ToString());
                                        list.Add(jtms["fileName"].ToString());
                                        str = string.Join(",", list);
                                    }
                                    Zlxxdic.Add("Msb", str);
                                }
                                else
                                {
                                    Zlxxdic.Add("Msb", "无附件");
                                }
                            }
                            else
                            {
                                Zlxxdic.Add("Msb", "无附件");
                            }

                            break;
                    }
                }
                string time = "2022-01-01";
                Jbxxdic.Add("uuid", uuid);
                Gwxxdic.Add("uuid", uuid);
                Zlxxdic.Add("Jbxxid", uuid);
                Zlxxdic.Add("Lytime", Convert.ToDateTime(time));
                Zlxxdic.Add("Result", "行政级别:"+a);
                Zlxxdic.Add("ResultBz", "无附件");
                Zlxx zl = ConvertDic<Zlxx>(Zlxxdic);
                if (Zlxxdic != null)
                {
                    _db.zlxxes.Add(zl);
                    _db.SaveChanges();
                }

                hr_gwxx gw = ConvertDic<hr_gwxx>(Gwxxdic);
                if(gw != null)
                {
                    _db.hr_gwxx.Add(gw);
                    _db.SaveChanges();
                }

                hr_jbxx hrj = ConvertDic<hr_jbxx>(Jbxxdic);
                if(hrj != null)
                {
                    _db.hr_jbxx.Add(hrj);
                    _db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                WriteLog("AddZLinfo:" + ex.Message, "ErrLog", true);
            }
        }
        //二同步数据到人事系统
        public void DataToHR(string processInstanceId)
        {
            
            WriteLog("DataToHR", "SPLog", true);
            try
            {
                string form_component_values = Getformcomponentvalues(processInstanceId);

                var formData = JArray.Parse(form_component_values);
                Dictionary<string, object> DicForm = new();
                Dictionary<string, object> DicFormhyzk = new();
                Dictionary<string, object> DicFormjyxx = new();
                Dictionary<string, object> DicFormgzjl = new();
                Dictionary<string, object> DicFormjtqk = new();
                Dictionary<string, object> DicFormrzrq = new();
                Dictionary<string, object> DicFormzs = new();

                string name = "";
                string userid = null;
                foreach (var Form in formData)
                {
                    switch (Form["name"].ToString())
                    {
                        case "姓名":
                            name = Form["value"].ToString();
                            DicForm.Add("name", Form["value"].ToString());
                            break;
                        case "userid":
                            userid = Form["value"].ToString();
                            break;
                        case "性别":
                            DicForm.Add("sex", Form["value"].ToString());
                            break;
                        case "年龄":
                            DicForm.Add("age", int.Parse(Form["value"].ToString()));
                            break;
                        case "出生日期":
                            DicForm.Add("birthAge", Form["value"].ToString());
                            break;
                        case "血型":
                            DicForm.Add("bloodtype", Form["value"].ToString());
                            break;
                        case "民族":
                            DicForm.Add("areas", Form["value"].ToString());
                            break;
                        case "电话":
                            DicForm.Add("phonenumber", Form["value"].ToString());
                            break;
                        case "身份证":
                            DicForm.Add("idNumber", Form["value"].ToString());
                            break;
                        case "籍贯":
                            var jg = Form["value"].ToString().Split(',');

                            switch (jg[0])
                            {
                                case "北京":
                                    jg[0] = "北京市";
                                    break;
                                case "天津":
                                    jg[0] = "天津市";
                                    break;
                                case "上海":
                                    jg[0] = "上海市";
                                    break;
                                case "重庆":
                                    jg[0] = "重庆市";
                                    break;
                            }

                            jg[0] = getAreaID(jg[0]);
                            jg[1] = getAreaID(jg[1]);
                            WriteLog(jg[1], "JbxxLog", true);
                            DicForm.Add("sheng", jg[0]);
                            DicForm.Add("shi", jg[1]);
                           
                            WriteLog(DateTime.Now + "籍贯" + Form["value"].ToString(), "JbxxLog", true);

                            break;
                        case "户籍所在地":
                            var hj = Form["value"].ToString().Split(',');

                            switch (hj[0])
                            {
                                case "北京":
                                    hj[0] = "北京市";
                                    break;
                                case "天津":
                                    hj[0] = "天津市";
                                    break;
                                case "上海":
                                    hj[0] = "上海市";
                                    break;
                                case "重庆":
                                    hj[0] = "重庆市";
                                    break;
                            }
                            hj[0] = getAreaID(hj[0]);
                            hj[1] = getAreaID(hj[1]);
                            hj[2] = getAreaID(hj[2]);

                            DicForm.Add("hjsheng", hj[0]);
                            DicForm.Add("hjshi", hj[1]);
                            DicForm.Add("hjxian", hj[2]);
                            DicForm.Add("hjszplace", hj[3] + hj[4]);
                                                       
                            WriteLog(DateTime.Now + "户籍" + Form["value"].ToString(), "JbxxLog", true);

                            break;
                        case "现居住地":
                            var xj = Form["value"].ToString().Split(',');

                            switch (xj[0])
                            {
                                case "北京":
                                    xj[0] = "北京市";
                                    break;
                                case "天津":
                                    xj[0] = "天津市";
                                    break;
                                case "上海":
                                    xj[0] = "上海市";
                                    break;
                                case "重庆":
                                    xj[0] = "重庆市";
                                    break;
                            }
                            xj[0] = getAreaID(xj[0]);
                            xj[1] = getAreaID(xj[1]);
                            xj[2] = getAreaID(xj[2]);

                            DicForm.Add("xjsheng", xj[0]);
                            DicForm.Add("xjshi", xj[1]);
                            DicForm.Add("xjxian", xj[2]);
                            DicForm.Add("actuallyplace", xj[3] + xj[4]);
                            WriteLog(DateTime.Now + "子女数量" + Form["value"].ToString(), "JbxxLog", true);

                            break;
                        case "政治面貌":
                            DicForm.Add("zzmm", Form["value"].ToString());
                            WriteLog(DateTime.Now + "现居" + Form["value"].ToString(), "JbxxLog", true);

                            break;
                        case "参加党派时间":
                            DicForm.Add("dateOfJointheParty", Form["value"].ToString());
                            WriteLog(DateTime.Now + "党" + Form["value"].ToString(), "JbxxLog", true);

                            break;
                        case "婚姻状况":
                            if (Form["value"].ToString() == "未婚")
                            {
                                DicFormhyzk.Add("hyzk", "0");
                            }
                            else if (Form["value"].ToString() == "已婚")
                            {
                                DicFormhyzk.Add("hyzk", "1");
                            }
                            else if (Form["value"].ToString() == "再婚")
                            {
                                DicFormhyzk.Add("hyzk", "2");
                            }
                            else if (Form["value"].ToString() == "离异")
                            {
                                DicFormhyzk.Add("hyzk", "3");
                            }
                            else if (Form["value"].ToString() == "丧偶")
                            {
                                DicFormhyzk.Add("hyzk", "4");
                            }
                            else if (Form["value"].ToString() == "其他")
                            {
                                DicFormhyzk.Add("hyzk", "5");
                            }
                            WriteLog(DateTime.Now + "婚姻情况" + Form["value"].ToString(), "JbxxLog", true);

                            break;
                        case "生育情况":
                            if (Form["value"].ToString() == "未育")
                            {
                                DicFormhyzk.Add("shengyu", "0");
                                DicFormhyzk.Add("kidsnumber", "0");
                            }
                            else
                            {
                                DicFormhyzk.Add("shengyu", "1");
                            }
                            WriteLog(DateTime.Now + "生育情况" + Form["value"].ToString(), "JbxxLog", true);

                            break;

                        case "子女数量":
                            if (Form["value"].ToString() == "一孩")
                            {
                                DicFormhyzk.Add("kidsnumber", "1");
                            }
                            else if (Form["value"].ToString() == "二孩")
                            {
                                DicFormhyzk.Add("kidsnumber", "2");
                            }
                            else if (Form["value"].ToString() == "三孩")
                            {
                                DicFormhyzk.Add("kidsnumber", "3");
                            }
                            else if (Form["value"].ToString() == "四孩")
                            {
                                DicFormhyzk.Add("kidsnumber", "4");
                            }
                            else if (Form["value"].ToString() == "其他")
                            {
                                DicFormhyzk.Add("kidsnumber", "0");
                            }
                            WriteLog(DateTime.Now+ "子女数量" + Form["value"].ToString(), "JbxxLog", true);
                            break;
                        case "教育信息":
                            //var arr = @"{'starttime', 'endtime', 'school, 'yuanxi', 'xuexixingshi', 'zhengshunumber', 'xuexinresult', 'fileUrl', 'xuexinreason', 'notpassresult'}";                        
                            var aa = Form["value"].ToString();
                            var ja = JArray.Parse(aa);
                            JObject jo = JObject.Parse(ja[0].ToString());
                            DicFormjyxx.Add("starttime", jo["rowValue"][0]["value"].ToString());
                            DicFormjyxx.Add("endtime", jo["rowValue"][1]["value"].ToString());
                            DicFormjyxx.Add("school", jo["rowValue"][2]["value"].ToString());
                            DicFormjyxx.Add("yuanxi", jo["rowValue"][3]["value"].ToString());
                            DicFormjyxx.Add("xuexixingshi", jo["rowValue"][4]["value"].ToString());
                            DicFormjyxx.Add("zhengshunumber", jo["rowValue"][5]["value"].ToString());
                            DicFormjyxx.Add("xuexinresult", jo["rowValue"][6]["value"].ToString());
                            if (aa.Contains("已查实"))
                            {
                                var jarr = JArray.Parse(jo["rowValue"][7]["value"].ToString());
                                string str0 = null;
                                List<string> list0 = new List<string>();
                                for(var i = 0; i < jarr.Count; i++)
                                {
                                    list0.Add(jo["rowValue"][7]["value"][i]["fileName"].ToString());
                                    str0 = string.Join(",", list0.ToString());
                                }
                                DicFormjyxx.Add("fileUrl", str0);

                            }
                            else if (aa.Contains("未查实") && (aa.Contains("于2001年前获得的学历证书、学信网无法查验") || aa.Contains("学历造假")))
                            {
                                DicFormjyxx.Add("notpassresult", jo["rowValue"][7]["value"].ToString());
                            }
                            else if (aa.Contains("未查实") && aa.Contains("其他原因"))
                            {
                                DicFormjyxx.Add("notpassresult", jo["rowValue"][7]["value"].ToString());
                                DicFormjyxx.Add("xuexinreason", jo["rowValue"][8]["value"].ToString());
                            }
                            break;

                        case "工作经历":
                            var gzval = Form["value"].ToString();
                            var jagz = JArray.Parse(gzval);
                            JObject jogz = JObject.Parse(jagz[0].ToString());
                            DicFormgzjl.Add("starttime", jogz["rowValue"][0]["value"].ToString());
                            DicFormgzjl.Add("endtime", jogz["rowValue"][1]["value"].ToString());
                            DicFormgzjl.Add("workplace", jogz["rowValue"][2]["value"].ToString());
                            DicFormgzjl.Add("department", jogz["rowValue"][3]["value"].ToString());
                            break;
                        case "家庭情况":
                            var jtval = Form["value"].ToString();
                            var jajt = JArray.Parse(jtval);
                            JObject jojt = JObject.Parse(jajt[0].ToString());
                            DicFormjtqk.Add("relation", jojt["rowValue"][0]["value"].ToString());
                            DicFormjtqk.Add("name", jojt["rowValue"][1]["value"].ToString());
                            DicFormjtqk.Add("workplace", jojt["rowValue"][2]["value"].ToString());
                            DicFormjtqk.Add("birthday", jojt["rowValue"][3]["value"].ToString());
                            DicFormjtqk.Add("adresse", jojt["rowValue"][4]["value"].ToString());
                            DicFormjtqk.Add("phone", jojt["rowValue"][5]["value"].ToString());
                            break;
                        case "职称、证书":
                            var zczsval = Form["value"].ToString();
                            var jazczs = JArray.Parse(zczsval);
                            JObject jozczs = JObject.Parse(jazczs[0].ToString());

                            JToken jot = JToken.Parse(Form["value"].ToString());
                            var aaa = jot[0]["rowValue"];
                            var abc = aaa[2]["value"];
                            JArray jams = JArray.Parse(jot[0]["rowValue"][2]["value"].ToString());

                            WriteLog(" 职称、证书 " + jozczs["rowValue"][0]["value"].ToString() + "  " + jozczs["rowValue"][1]["value"].ToString() + jozczs["rowValue"][2]["value"][0]["fileName"].ToString(), "JbxxLog", true);

                            DicFormzs.Add("zsname", jozczs["rowValue"][0]["value"].ToString());
                            DicFormzs.Add("getdate", Convert.ToDateTime(jozczs["rowValue"][1]["value"].ToString()));
                            var jarr1 = JArray.Parse(jozczs["rowValue"][2]["value"].ToString());
                            List<string> jarr2 = new List<string>();
                            string str = null;
                            for (var i = 0; i < jarr1.Count; i++)
                            {
                                jarr2.Add(abc[i]["fileName"].ToString());
                                str = string.Join(",", jarr2);
                            }
                            DicFormzs.Add("zsfj", str);

                            break;

                        case "入职日期":
                            DicFormrzrq.Add("workstarttime", Form["value"].ToString());
                            break;
                    }

                }
                WriteLog(DateTime.Now+"获取userid:" +userid,"JbxxLog",true);
                var phone =  GetUserPhone(userid);
                WriteLog(DateTime.Now+"获取phone:" + phone, "JbxxLog", true);

                var data =  _db.hr_jbxx.Where(p => p.phonenumber == phone).SingleOrDefault();
                var uuid = data.uuid;
                WriteLog(DateTime.Now+"uuid2: "+uuid, "JbxxLog", true);
                DicForm.Add("uuid", uuid);
                DicFormhyzk.Add("uuid", uuid);
                DicFormjyxx.Add("uuid", uuid);
                DicFormgzjl.Add("uuid", uuid);
                DicFormjtqk.Add("uuid", uuid);
                DicFormrzrq.Add("uuid", uuid);

                DicFormzs.Add("jbxxid", uuid);
                DicFormzs.Add("Id", Guid.NewGuid().ToString());

                var datajbxx = _db.hr_jbxx.Where(p => p.uuid == uuid).FirstOrDefault();
                DicForm.Add("Id", datajbxx.Id);
                hr_jbxx hr = ConvertDic<hr_jbxx>(DicForm);
                _db.hr_jbxx.Remove(datajbxx);
                _db.hr_jbxx.Add(hr);
                //_db.Entry(hr).State = EntityState.Modified;                
                _db.SaveChanges();
                

                hr_hyzk hy = ConvertDic<hr_hyzk>(DicFormhyzk);
                if (DicFormhyzk != null)
                {
                    _db.hr_hyzk.Add(hy);
                    _db.SaveChanges();
                }
                hr_jyxx jy = ConvertDic<hr_jyxx>(DicFormjyxx);
                if (DicFormjyxx != null)
                {
                    _db.hr_jyxx.Add(jy);
                    _db.SaveChanges();
                }
                hr_gzjl gz = ConvertDic<hr_gzjl>(DicFormgzjl);
                if (DicForm != null)
                {
                    _db.hr_gzjl.Add(gz);
                    _db.SaveChanges();
                }
                
                hr_jtzk jt = ConvertDic<hr_jtzk>(DicFormjtqk);
                if (DicFormjtqk != null)
                {
                    _db.hr_jtzk.Add(jt);
                    _db.SaveChanges();
                }

                var datagwxx = _db.hr_gwxx.Where(p => p.uuid == uuid).SingleOrDefault();
                DicFormrzrq.Add("Id", datagwxx.Id);
                hr_gwxx gw = ConvertDic<hr_gwxx>(DicFormrzrq);
                _db.hr_gwxx.Remove(datagwxx);
                _db.hr_gwxx.Add(datagwxx);
                //_db.Entry(gw).State = EntityState.Modified;               
                _db.SaveChanges();
                
                hr_zsxx zs = ConvertDic<hr_zsxx>(DicFormzs);
                WriteLog("1 " + zs.jbxxid + " 2 " + zs.zsfj + " 3 " + zs.zsname + " 4 " + zs.Id + " 5 " + zs.getdate, "ZSLog", true);
                if (DicFormzs != null)
                {
                    _db.hr_zsxx.Add(zs);
                    _db.SaveChanges();
                }

            }
            catch (Exception e)
            {
                WriteLog(DateTime.Now + " 错误信息：" + e.Message, "ErrLog", true);
            }

        }
        //三 离职审批
        public void Leave(string processInstanceId)
        {
            WriteLog("Leave", "LeaveLog", true);
            try
            {
                string form_component_values = Getformcomponentvalues(processInstanceId);
                var formData = JArray.Parse(form_component_values);
                Dictionary<string, object> dicleave = new();

                string userid = null;
                foreach (var Form in formData)
                {
                    if (Form.ToString().Contains("name"))
                    {
                        switch (Form["name"].ToString())
                        {
                            case "userid":
                                userid = Form["value"].ToString();
                                break;
                            case "类别":
                                if (Form["value"].ToString() == "离职")
                                {
                                    dicleave.Add("JobStatus", "离职");
                                }
                                break;
                            case "调/离职日期":
                                dicleave.Add("LeaveDate",Convert.ToDateTime(Form["value"].ToString()));
                                break;
                            case "调/离职原因":
                                dicleave.Add("leaveNote", Form["value"].ToString());
                                break;
                        }
                    }
                }

                var phone = GetUserPhone(userid);
                WriteLog("phone:"+phone, "LeaveLog", true);
                var dataleave = _db.hr_jbxx.Where(p=>p.phonenumber == phone).FirstOrDefault();
                WriteLog("dataleave.uuid:"+ dataleave.uuid, "LeaveLog", true);
                var uuid = dataleave.uuid;
                WriteLog("uuid:"+ uuid, "LeaveLog", true);

                dicleave.Add("jbxxid", uuid);
                dicleave.Add("Id",Guid.NewGuid().ToString());
                hr_ldgx ldgx = ConvertDic<hr_ldgx>(dicleave);
                WriteLog(ldgx.Id + " " + ldgx.jbxxid + " " + ldgx.JobStatus + " " + ldgx.LeaveDate + "" + ldgx.leaveNote, "LeaveLog",true);
                if (dicleave != null)
                {
                    _db.hr_ldgx.Add(ldgx);
                    _db.SaveChanges();
                }                
            }
            catch(Exception ex)
            {
                WriteLog(ex.Message,"ErrLog",true);
            }
        }
        //四劳动续签
        public void Sign(string processInstanceId)
        {
            try
            {
                string form_component_values = Getformcomponentvalues(processInstanceId);
                var formData = JArray.Parse(form_component_values);
                Dictionary<string, object> dicsign = new();
                dicsign.Add("Id",Guid.NewGuid().ToString());
               

                string userid = null;
                foreach(var form in formData)
                {
                    if(form.ToString().Contains("name") && form["value"].ToString() != "null")
                    { 
                        switch (form["name"].ToString())
                        {
                            case "userid":
                                userid = form["value"].ToString();
                                break;
                            case "合同类型":
                                dicsign.Add("type", form["value"].ToString());
                                break;
                            case "合同期限":
                                dicsign.Add("year", form["value"].ToString());
                                break;
                            case "开始时间":
                                dicsign.Add("sdate", Convert.ToDateTime(form["value"].ToString()));
                                break;
                            case "结束时间":
                                if(form.ToString().Contains("name") && (form["value"].ToString()!= "null"))
                                { 
                                    dicsign.Add("edate", Convert.ToDateTime(form["value"].ToString()));
                                }
                                break ;
                        }
                    }
                }
                var phone = GetUserPhone(userid);
                var datajbxx = _db.hr_jbxx.Where(p => p.phonenumber == phone).FirstOrDefault();
                dicsign.Add("jbxxid", datajbxx.uuid);

                hr_ldht ldht = ConvertDic<hr_ldht>(dicsign);
                if (ModelState.IsValid)
                {
                    _db.hr_ldht.Add(ldht);
                    _db.SaveChanges();
                }


            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "ErrLog", true);
            }
        }
        //五 员工转正
        public void ZhuanZ(string processInstanceId)
        {
            try
            {
                string form_component_values = Getformcomponentvalues(processInstanceId);
                var formData = JArray.Parse(form_component_values);
                Dictionary<string, object> diczz = new();

                string userid = null;
                foreach(var form in formData)
                {
                    if(form.ToString().Contains("name"))
                    { 
                        switch (form["name"].ToString())
                        {
                            case "userid":
                                userid = form["value"].ToString();
                                break;
                            case "试用期":
                                diczz.Add("syq",form["value"].ToString());
                                break;
                            case "入职日期":
                                diczz.Add("sdate", Convert.ToDateTime(form["value"].ToString()));
                                break;
                            case "转正日期":
                                diczz.Add("edate", Convert.ToDateTime(form["value"].ToString()));
                                break;
                            case "转正类型":
                                diczz.Add("zzlx", form["value"].ToString());
                                break;
                            case "非正常转正说明":
                                if (form.ToString().Contains("value") && form["value"].ToString() != "null")
                                {
                                    diczz.Add("zznote", form["value"].ToString());
                                }
                                break;
                        }
                    }
                }
                var phone = GetUserPhone(userid);
                var datajbxx = _db.hr_jbxx.Where(p => p.phonenumber == phone).FirstOrDefault();

                diczz.Add("Id", Guid.NewGuid().ToString());
                diczz.Add("jbxxid", datajbxx.uuid);
                hr_syq syq = ConvertDic<hr_syq>(diczz);
                if (ModelState.IsValid)
                {
                    _db.hr_syq.Add(syq);
                    _db.SaveChanges();
                }
            }catch(Exception ex)
            {
                WriteLog(ex.Message, "ErrLog", true);
            }
        }

        //浪潮
        public void DToL(string processInstanceId)
        {

        }
    }
}
